import fs from "fs";
import defaultConfig from "../config/defaultConfig.js";
import { getBusinessProjectFilePath, getThisProjectFilePath } from "./index.js";

/**
 * 获取 package-cli-service 配置
 * 用户配置文件 || package-cli-service.config.js
 * @returns {Promise<{}>}
 */
const getPkgToolsConfig = async () => {
  let businessCustomPkgToolsConfigFile;
  const configPath = getBusinessProjectFilePath(
    businessCustomPkgToolsConfigFile || "package-cli-service.config.js"
  );
  let configData = {};
  if (fs.existsSync(configPath)) {
    // delete require.cache[require.resolve(getBusinessProjectFilePath('package.json'))]
    // delete require.cache[require.resolve(configPath)]

    const { default: config } = await import(configPath);
    if (typeof config === "function") {
      configData = config();
    } else {
      configData = config;
    }
  }

  const outputDir = configData.outputDir || defaultConfig.outputDir;
  configData = {
    ...defaultConfig,
    ...configData,
    outputPath: getBusinessProjectFilePath(outputDir),
    outputDir: outputDir,
    outputEsDir: `${outputDir}/${defaultConfig.esDir}`,
    outputCjsDir: `${outputDir}/${defaultConfig.cjsDir}`,
    outputUmdDir: `${outputDir}/${defaultConfig.umdDir}`,
    storybookConfig: {
      ...defaultConfig.storybook,
      ...configData.storybook,
    },
  };

  return configData;
};
export default getPkgToolsConfig;

/**
 * 获取业务侧 package.json
 * @returns {any}     packageJson
 */
export const getPackageJson = () => {
  const thisProjectPackageJsonPath = getBusinessProjectFilePath("package.json");
  return JSON.parse(
    fs.readFileSync(thisProjectPackageJsonPath, { encoding: "utf8" })
  );
};
